package com.hs.service;

import com.hs.VO.LessonPO;
import com.hs.VO.LessonStudentVO;
import com.hs.config.PageObj;
import com.hs.dao.*;
import com.hs.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class StudentService {
    @Autowired
    StudentMapper studentMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ClassLessonIssueMapper classLessonIssueMapper;
    @Autowired
    ClassLessonMapper classLessonMapper;
    @Autowired
    IssueFlushMapper issueFlushMapper;
    @Autowired
    LessonMapper lessonMapper;


    public int insertSelective(Student record){
        record.setCreateTime(new Date());
        int i =  studentMapper.insertSelective(record);
        return i;
    }

    /**
     * update student classId
     * @param record
     * @return
     */
    public int updateCLassId(Student record){
        Student student = new Student();
        student.setId(record.getId());
        student.setClassId(record.getClassId());
        student.setUpdateTime(new Date());
        int i =  studentMapper.updateByPrimaryKeySelective(student);
        return i;
    }

    /**
     * 参与 粒度在class_lesson_issue
     * 数据在issue_flush
     * @param record
     * @return
     */
    @Transactional
    public int handInLesson(LessonPO record){
        //获取 本期的基础数据 ClassLessonIssue
        ClassLessonIssue classLessonIssue = classLessonIssueMapper.selectByPrimaryKey(record.getClassLessonIssueId());
        if(classLessonIssue == null){
            return 0;
        }
        if(classLessonIssue.getStatus() == 1){
            return 0;
        }
        //获取 LessonStudentVO（已classLesson为粒度，包含model信息，model中有基础课程配置的参数 期数 和限时结束时间）
        //classLessonId == classLesson的i d
        record.setId(record.getClassLessonId());
        List<LessonStudentVO> list = lessonMapper.selectStudentLesson(record);
        if(list == null || list.size() == 0){
            return 0;
        }
        LessonStudentVO item = list.get(0);
        //查询所有这期的IssueFLush数据，是否结束和结束都要用到。
        IssueFlush pa = new IssueFlush();
        pa.setOrderDesc("  order by create_time desc");
        pa.setIssueId(classLessonIssue.getId());
        List<IssueFlush> flushes = issueFlushMapper.selectByCondition(pa);


        //点击时结束判断本期 更新  classLessonIssue
        long l = System.currentTimeMillis() - classLessonIssue.getCreateTime().getTime();
        //如果到了classLessonIssue结束时间  结束classLessonIssue
        if(l > 1000 * 60 * item.getLimitTime()){ //model中的限时结束时间
            classLessonIssue.setUpdateTime(new Date());//更新时间
            classLessonIssue.setStatus(1);//设为结束
            //获取如果IssueFlush为空最新的需求的Q和 Pice
            if(flushes != null && flushes.size() != 0){
                IssueFlush issueFlushEnd = flushes.get(0);
                classLessonIssue.setEndQ(issueFlushEnd.getBQ());
                classLessonIssue.setEndP(issueFlushEnd.getBP1());  //确定是需求价格
                classLessonIssue.setUpdateTime(new Date());
                int j = classLessonIssueMapper.updateByPrimaryKeySelective(classLessonIssue);
                if(j > 0 ){
                    log.info("结束本期数据，更新本期数据。"+classLessonIssue.getIssue());
                }else {
                    log.error("结束本期数据，更新本期数据失败。"+classLessonIssue.getIssue());
                }
            }else{
                //如果IssueFlush为空 则未开始 就结束了，没产生流水数据，不再获取IssueFlush,否则null指针。
                //直接默认 0   0 结束  以便后期 需要 0 不再偏移。
                classLessonIssue.setEndQ(0);
                classLessonIssue.setEndP(0.0);
                int j = classLessonIssueMapper.updateByPrimaryKeySelective(classLessonIssue);
                if(j > 0 ){
                    log.info("本期无数据结束。"+classLessonIssue.getIssue());
                }else {
                    log.error("结束本期数据，更新本期数据失败。"+classLessonIssue.getIssue());
                }
            }
            //如果classLessonIssue 到了 12期， 12期结束 更新课程的状态classLesson课程状态为2 结束
            if(classLessonIssue.getIssue() == item.getIssue()){ //model中的总期数
                ClassLesson classLesson = new ClassLesson();
                classLesson.setStatus(2);
                classLesson.setId(classLessonIssue.getClassLessonId());
                int k = classLessonMapper.updateByPrimaryKeySelective(classLesson);
                if(k > 0){
                    log.info("更新班级课程,classLessonId = "+classLessonIssue.getClassLessonId());
                }else{

                    log.error("更新班级课程失败,classLessonId = "+classLessonIssue.getClassLessonId());
                }

            }
            return 0;
        }
        //没有到结束时间 则 生成IssueFlush数据
        //递增Q  插入 IssueFlush
        if(flushes == null || flushes.size() == 0){
            record.setQ(100);//无数据则是未结束的第一次参与，默认 100（Q）
        }else{
            record.setQ(100+flushes.get(0).getBQ());
        }

        //运算要插入的数据
        Integer needA = classLessonIssue.getNeedA();
        Integer needB = classLessonIssue.getNeedB();
        Integer needTrid = classLessonIssue.getNeedTrid();
        Integer provideA = classLessonIssue.getProvideA();
        Integer provideB = classLessonIssue.getProvideB();
        Integer provideTrid = classLessonIssue.getProvideTrid();
        int classLessonIssueId = classLessonIssue.getId();
        Integer Q = record.getQ();


        //公式运算
//        Double bp1 = (needA * Q + needB)/needTrid;
//        Double bp2 = (provideA * Q + provideB)/provideTrid;

        Double bp1 = (double)Math.round(needA * Q + needB)/needTrid;
        Double bp2 =  (double) Math.round(provideA * Q + provideB)/provideTrid;
        Double bpp = bp1 - bp2;

        //insert
        IssueFlush issueFlush = new IssueFlush();
        issueFlush.setIssueId(classLessonIssueId);
        issueFlush.setBQ(Q);
        issueFlush.setBP1(bp1);
        issueFlush.setBP2(bp2);
        issueFlush.setBPP(bpp);
        issueFlush.setCreateTime(new Date());
        int i =  issueFlushMapper.insertSelective(issueFlush);
        return i;
    }
    public List<Student> selectByCondition(Student record){
        List<Student> studentList =  studentMapper.selectByCondition(record);
        return studentList;
    }
    public int selectByConditionCount(Student record){
       int count =  studentMapper.selectByConditionCount(record);
        return count;
    }



    public PageObj page(Student item){
        int total = studentMapper.selectByConditionCount(item);
        if(total == 0){
            return new PageObj(item.getCurrentPage(), item.getPageSize(),total,null);
        }
        List<Student> list = studentMapper.selectByCondition(item);
        return new PageObj(item.getCurrentPage(), item.getPageSize(),total,list);
    }

    public int removeStudentClass(Integer id){
        Student student = studentMapper.selectByPrimaryKey(id);
        student.setClassId(null);
        student.setId(id);
        int i = studentMapper.updateByPrimaryKey(student);
        return i;

    }

    public static void main(String[] args) {
//        Double b = 10.0/3;
//        b = (double)Math.round(b*100)/100;
//        System.out.println(b);
//        System.out.println(b - 1.2);
//        System.out.println(b.intValue());
//        System.out.println((double) Math.round(350)/100);
//        System.out.println((double) Math.round((1 * 300 + 400))/200);


        Double bp2 =  (double) Math.round(1 * 300 + 400)/200;
        System.out.println(bp2);



    }

}
